import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { diskStorage } from 'multer';
import * as fs from 'fs';
import * as path from 'path';
import {
  UPLOAD_DIR,
  fileFilter,
  sanitizeFileName,
} from './utils/file-upload.utils';
import { FileResponseDto } from './dto/file-response.dto';

@Injectable()
export class ComLocalUploadService {
  // 获取 Multer 配置
  getMulterConfig() {
    return {
      storage: diskStorage({
        destination: UPLOAD_DIR,
        filename: (req, file, callback) => {
          const cleanFileName = sanitizeFileName(file.originalname);
          callback(null, cleanFileName);
        },
      }),
      fileFilter: fileFilter(),
      limits: {
        fileSize: 1024 * 1024 * 1, // 1MB 限制
      },
    };
  }
  // 保存文件并返回文件信息
  async saveFile(file: Express.Multer.File): Promise<FileResponseDto> {
    if (!file) {
      throw new HttpException('未上传文件', HttpStatus.BAD_REQUEST);
    }

    // 创建上传目录（如果不存在）
    if (!fs.existsSync(UPLOAD_DIR)) {
      fs.mkdirSync(UPLOAD_DIR, { recursive: true });
    }

    const cleanFileName = sanitizeFileName(file.originalname);

    // 生成完整的可访问URL
    let addr = '';
    if (process.env.NOWENV === 'prod') {
      // 地址
      addr = process.env.FILE_EXPOSE_IP;
    } else {
      // 地址
      addr = `http://${process.env.SERVER_ADDRESS}:${process.env.SERVER_PORT}`;
    }

    const fileUrl = `${addr}/uploads/${cleanFileName}`;

    return {
      fileName: cleanFileName,
      filePath: fileUrl,
    };
  }
}
